import axios from 'axios';

/**
 * 维修工单相关API
 */
export const repairService = {
    // 获取维修工单列表
    getList(params) {
        return axios.get('/api/services/repairs/', { params });
    },

    // 获取维修工单详情
    getDetail(id) {
        return axios.get(`/api/services/repair/${id}/`);
    },

    // 更新维修工单状态
    updateStatus(id, status) {
        return axios.post(`/api/services/repair/${id}/status/`, { status });
    },

    // 添加维修工单处理记录
    addRecord(id, content, images = []) {
        const formData = new FormData();
        formData.append('content', content);
        if (images && images.length > 0) {
            images.forEach((image, index) => {
                formData.append(`image_${index}`, image);
            });
        }
        return axios.post(`/api/services/repair/${id}/record/`, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
        });
    }
};

/**
 * 保洁工单相关API
 */
export const cleaningService = {
    // 获取保洁工单列表
    getList(params) {
        return axios.get('/api/services/cleaning-bookings/', { params });
    },

    // 获取保洁工单详情
    getDetail(id) {
        return axios.get(`/api/services/cleaning/${id}/`);
    },

    // 更新保洁工单状态
    updateStatus(id, status) {
        return axios.post(`/api/services/cleaning/${id}/status/`, { status });
    },

    // 添加保洁工单处理记录
    addRecord(id, content, images = []) {
        const formData = new FormData();
        formData.append('content', content);
        if (images && images.length > 0) {
            images.forEach((image, index) => {
                formData.append(`image_${index}`, image);
            });
        }
        return axios.post(`/api/services/cleaning/${id}/record/`, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
        });
    }
};

/**
 * 送水工单相关API
 */
export const waterService = {
    // 获取送水工单列表
    getList(params) {
        return axios.get('/api/services/water-deliveries/', { params });
    },

    // 获取送水工单详情
    getDetail(id) {
        return axios.get(`/api/services/water/${id}/`);
    },

    // 更新送水工单状态
    updateStatus(id, status) {
        return axios.post(`/api/services/water/${id}/status/`, { status });
    },

    // 添加送水工单处理记录
    addRecord(id, content, images = []) {
        const formData = new FormData();
        formData.append('content', content);
        if (images && images.length > 0) {
            images.forEach((image, index) => {
                formData.append(`image_${index}`, image);
            });
        }
        return axios.post(`/api/services/water/${id}/record/`, formData, {
            headers: { 'Content-Type': 'multipart/form-data' }
        });
    }
};

/**
 * 工作台相关API
 */
export const dashboardService = {
    /**
     * 获取待办任务列表
     * @param {Object} params 请求参数
     * @returns {Promise}
     */
    getTodoTasks(params) {
        return axios.get('/api/services/staff/tasks/todo', { params });
    },

    /**
     * 获取可接单任务列表
     * @param {Object} params 请求参数
     */
    getAvailableTasks(params) {
        // 确保params包含必要的参数
        const defaultParams = {
            page: 1,
            pageSize: 10,
            type: 'cleaning'  // 默认保洁类型
        };

        const mergedParams = { ...defaultParams, ...params };

        // 添加调试日志
        console.log('发送获取可接单任务请求，参数:', mergedParams);

        return axios.get('/api/services/staff/tasks/available', { params: mergedParams });
    },

    /**
     * 获取已完成任务列表
     * @param {Object} params 请求参数
     * @returns {Promise}
     */
    getCompletedTasks(params) {
        return axios.get('/api/services/staff/tasks/completed', { params });
    },

    /**
     * 获取任务详情
     * @param {number} id 任务ID
     * @param {string} type 任务类型(cleaning/repair/water)
     * @returns {Promise}
     */
    getTaskDetail(id, type) {
        if (!id || !type) {
            console.error('获取任务详情缺少必要参数');
            return Promise.reject('缺少必要参数');
        }

        let apiUrl = '';
        switch (type) {
            case 'cleaning':
                apiUrl = `/api/services/cleaning/${id}/`;
                break;
            case 'repair':
                apiUrl = `/api/services/repair/${id}/`;
                break;
            case 'water':
                apiUrl = `/api/services/water/${id}/`;
                break;
            default:
                console.error('未知的任务类型');
                return Promise.reject('未知的任务类型');
        }

        return axios.get(apiUrl);
    },

    /**
     * 获取业绩统计数据
     * @param {string} period 统计周期(today/month)
     * @returns {Promise}
     */
    getPerformanceStats(period) {
        return axios.get('/api/services/staff/performance', { params: { period } });
    },

    /**
     * 获取任务状态分布数据
     * @returns {Promise}
     */
    getTaskDistribution() {
        return axios.get('/api/services/staff/tasks/distribution');
    },

    /**
     * 获取最近7日工单完成量
     * @returns {Promise}
     */
    getWeeklyCompletionStats() {
        return axios.get('/api/services/staff/tasks/weekly-stats');
    }
};

/**
 * 获取所有工单统计数据
 * @returns {Promise} - 返回工单统计数据
 */
export function getTaskStats() {
    return axios.get('/api/services/stats/');
}

/**
 * 已弃用：旧的通用API方法，保留向后兼容
 */
export function updateTaskStatus(data) {
    const { id, type, status } = data;
    let apiUrl = '';

    switch (type) {
        case 'repair':
            apiUrl = `/api/services/repair/${id}/status/`;
            break;
        case 'cleaning':
            apiUrl = `/api/services/cleaning/${id}/status/`;
            break;
        case 'water':
            apiUrl = `/api/services/water/${id}/status/`;
            break;
        default:
            throw new Error('未知的工单类型');
    }

    return axios.post(apiUrl, { status });
}

export function addTaskRecord(data) {
    const { id, type, content } = data;
    let apiUrl = '';

    switch (type) {
        case 'repair':
            apiUrl = `/api/services/repair/${id}/record/`;
            break;
        case 'cleaning':
            apiUrl = `/api/services/cleaning/${id}/record/`;
            break;
        case 'water':
            apiUrl = `/api/services/water/${id}/record/`;
            break;
        default:
            throw new Error('未知的工单类型');
    }

    return axios.post(apiUrl, { content });
} 